<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="卡序列码" prop="cardCode">
        <el-input
          v-model="queryParams.cardCode"
          placeholder="请输入卡序列码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消耗状态" prop="consumeStatus">
        <el-select v-model="queryParams.consumeStatus" placeholder="请选择消耗状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.virtual_goods_consume_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="消耗时间" prop="consumeTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.consumeTime"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="可用状态" prop="isUsable">
        <el-select v-model="queryParams.isUsable" placeholder="请选择可用状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.virtual_goods_is_usable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:virtualGoodsStock:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:virtualGoodsStock:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:virtualGoodsStock:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['biz:virtualGoodsStock:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['biz:virtualGoodsStock:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="virtualGoodsStockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <el-table-column label="卡序列码" align="center" prop="cardCode" />
      <!-- <el-table-column label="卡密码" align="center" prop="cardPwd" /> -->
      <el-table-column label="消耗状态" align="center" prop="consumeStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.virtual_goods_consume_status" :value="scope.row.consumeStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="订单ID" align="center" prop="orderId" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="消耗时间" align="center" prop="consumeTime" width="180"/>
      <el-table-column label="可用状态" align="center" prop="isUsable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.virtual_goods_is_usable" :value="scope.row.isUsable"/>
        </template>
      </el-table-column>
      <el-table-column label="供应商" align="center" prop="tenantName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:virtualGoodsStock:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="updateIsUsable(scope.row)"
          >{{scope.row.isUsable==0?"解禁":"禁用"}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:virtualGoodsStock:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改虚拟商品库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="虚拟商品" prop="goodsId">
          <el-select v-model="form.goodsId" filterable placeholder="请选择"><br/>
            <el-option
              v-for="item in goodsList"
              :key="item.goodsId"
              :label="item.goodsName"
              :value="item.goodsId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卡序列码" prop="cardCode">
          <el-input v-model="form.cardCode" :maxlength="20" placeholder="请输入卡序列码" />
        </el-form-item>
        <el-form-item label="卡密码" prop="cardPwd">
          <el-input v-model="form.cardPwd" :maxlength="19" placeholder="请输入卡密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <template>
          虚拟商品：<el-select v-model="upload.goodsId" filterable placeholder="请选择"><br/>
            <el-option
              v-for="item in goodsList"
              :key="item.goodsId"
              :label="item.goodsName"
              :value="item.goodsId">
            </el-option>
          </el-select>
      </template>
      <p style="height: 10px;"></p>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport+'&goodsId=' + upload.goodsId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 导出对话框 -->
    <el-dialog title="导出" :visible.sync="isExport" width="400px" append-to-body>
      <el-input
          v-model="smsCode"
          placeholder="请输入验证码"
          clearable
          size="small"
        />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="smsCode?false:true" @click="submitExport">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listVirtualGoodsStock, getVirtualGoodsStock, delVirtualGoodsStock, addVirtualGoodsStock, updateVirtualGoodsStock, exportVirtualGoodsStock, importTemplate, importData, updateIsUsable,sendSmsVirtualGoodsStock } from "@/api/biz/goodsInfo/virtualGoodsStock";
import { getToken } from "@/utils/auth";
import { goodslistNotPage } from "@/api/biz/goodsInfo/goodsInfo";

export default {
  name: "VirtualGoodsStock",
  dicts: ['virtual_goods_consume_status', 'virtual_goods_is_usable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 虚拟商品库存表格数据
      virtualGoodsStockList: [],
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsId: null,
        goodsName: null,
        cardCode: null,
        cardPwd: null,
        consumeStatus: null,
        orderId: null,
        orderNo: null,
        consumeTime: null,
        starTime: null,
        endTime: null,
        isUsable: null,
        tenantId: null
      },
      // 表单参数
      form: {},
      // 数据导入参数
      upload: {
        // 是否显示弹出层（数据导入）
        open: false,
        // 弹出层标题（数据导入）
        title: "虚拟商品库存导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 商品ID
        goodsId: null,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/biz/virtualGoodsStock/importData"
      },
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: "商品不能为空", trigger: "change" }
        ],
        cardCode: [
          { required: true, message: "卡序列码不能为空", trigger: "change" }
        ],
        cardPwd: [
          { required: true, message: "卡密码不能为空", trigger: "change" }
        ],
      },
      isExport: false, // 导出对话框
      smsCode: "", // 验证码
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询虚拟商品库存列表 */
    getList() {
      this.loading = true;
      listVirtualGoodsStock(this.queryParams).then(response => {
        this.virtualGoodsStockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isExport = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        goodsName: null,
        cardCode: null,
        cardPwd: null,
        consumeStatus: null,
        orderId: null,
        orderNo: null,
        consumeTime: null,
        isUsable: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null,
        tenantId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if(this.queryParams.consumeTime!=null){
        this.queryParams.starTime=this.queryParams.consumeTime[0];
        this.queryParams.endTime=this.queryParams.consumeTime[1];
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加虚拟商品库存";
      this.getGoodsList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getVirtualGoodsStock(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改虚拟商品库存";
        this.getGoodsList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVirtualGoodsStock(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVirtualGoodsStock(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除虚拟商品库存编号为"' + ids + '"的数据项？').then(function() {
        return delVirtualGoodsStock(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      sendSmsVirtualGoodsStock().then(res=>{
        this.smsCode = "";
        this.isExport = true
      })
    },
    // 确定导出
    submitExport() {
      const queryParams = this.queryParams;
      queryParams.smsCode = this.smsCode;
      this.isExport = false;
      exportVirtualGoodsStock(queryParams).then(resp => {
        this.exportLoading = false;
        const blob = new Blob([resp],{type: 'application/vnd.ms-excel'});
        const fileName = 'mock虚拟测试.xlsx';
        const elink = document.createElement('a');// 创建a标签
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();// 点击下载
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);// 释放标签
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "虚拟商品库存导入";
      this.upload.open = true;
      this.getGoodsList();
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.$download.name(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(`<div style="max-height: 560px;overflow-y: auto;">${response.msg}</div>`, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 虚拟商品列表
    getGoodsList(){
      const param={
        "type":1
      }
      goodslistNotPage(param).then(res => {
        this.goodsList = res.data;
      })
    },
    updateIsUsable(row){
      const data={
        "id": row.id,
        "isUsable": row.isUsable==0?1:0
      }
      updateIsUsable(data).then(res => {
        if(res.code=200){
          this.getList();
          this.$modal.msgSuccess("操作成功");
        }else{
          this.$modal.msg(res.msg);
        }
      })
    }
  }
};
</script>
